package com.itmake.sample.limit.aspectj;

import com.itmake.sample.limit.enums.LimitType;
import com.itmake.sample.limit.annotation.Limit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 限流处理
 *
 * @author Amjacks
 * @since 2023/08/10
 */
@Aspect
@Component
public class LimitAspect {
    private static final Logger log = LoggerFactory.getLogger(LimitAspect.class);

    private RedisTemplate<Object, Object> redisTemplate;

    private RedisScript<Long> limitScript;

    @Resource
    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Resource
    public void setLimitScript(RedisScript<Long> limitScript) {
        this.limitScript = limitScript;
    }

    @Before("@annotation(limit)")
    public void doBefore(JoinPoint point, Limit limit) {
        String key = limit.key();
        int time = limit.time();
        int count = limit.count();

        // 处理
        StringBuilder stringBuffer = new StringBuilder(limit.key());
        if (limit.limitType() == LimitType.IP) {
            // @TODO 根据当前请求获取 ip 地址
            // String ip = ……;
            // stringBuffer.append(ip).append("-");
        }
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
        String combineKey = stringBuffer.toString();

        // 处理
        List<Object> keys = Collections.singletonList(combineKey);
        Long number = redisTemplate.execute(limitScript, keys, count, time);
        if (Objects.isNull(number) || number.intValue() > count) {
            throw new RuntimeException("访问过于频繁，请稍候再试");
        }
        log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), key);
    }
}
